package com.example.udp_test;

import android.text.TextUtils;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class CommunicateWordsWithUDP {

    private DatagramSocket socket = new DatagramSocket(1985);
    private String ipAddr;
//    private static final String password = "key";


    //对方的ip地址在构造方法中传入
    public CommunicateWordsWithUDP(String ipAddr) throws SocketException {
        this.ipAddr = ipAddr;
    }

    public void sendDataWithUDPSocket(String str) {
        try {
            InetAddress serverAddress = InetAddress.getByName(ipAddr);
            //加密
            String mSecretString = AESUtils3.encrypt(str, "password");
//            byte[] byteSend = mSecretString.getBytes();
//            Log.d("ss", mSecretString);
//            byte[] encryptStrByte = AESUtils3.encrypt(str.getBytes(), password);
//            byte data[] = mSecretString.getBytes();
//            Log.d("ss", "send:"+mSecretString );
            DatagramPacket packet = new DatagramPacket(mSecretString.getBytes(), mSecretString.length(), serverAddress,10025);
            socket.send(packet);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //接收消息的方法
    public void ServerReceviedByUdp() {
        DatagramSocket socket;
        try {
            socket = new DatagramSocket(10025);
            while (true) {
                byte data[] = new byte[4 * 1024];
                DatagramPacket packet = new DatagramPacket(data, data.length);
                socket.receive(packet);

                String result = new String(data, 0, packet.getLength());
                String mReceive = AESUtils3.decrypt(result, "password");
//                byte[] decrypt = AESUtils3.decrypt(data, password);
//                String mReceive = decrypt.toString();
//                Log.d("aa", result);
//                Log.d("bb", mReceive);
                if (!TextUtils.isEmpty(mReceive)) {
                    WordsEvent wordsEvent = new WordsEvent(mReceive);
                    EventBus.getDefault().post(wordsEvent);
                }
                System.out.println("收到信息为：" + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        socket.close();
        socket.disconnect();
    }
}



//package com.example.udp_test;
//
//import android.text.TextUtils;
//import android.util.Log;
//
//import com.example.udp_test.AESUtils3;
//import com.example.udp_test.WordsEvent;
//
//import org.greenrobot.eventbus.EventBus;
//
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.net.InetAddress;
//import java.net.SocketException;
//import java.net.UnknownHostException;
//
//public class CommunicateWordsWithUDP {
//    /**
//     * 使用DatagramSocket进行基于UDP的Socket通信
//     */
//    private DatagramSocket mSocket = new DatagramSocket(1985); // udp相关  端口号，确定指定应用程序,最好使用5000以后避免被占用
//    private String mIpAddr; // 确定到指定机器
//
//    /**
//     * 对方的ip地址在构造方法中传入
//     *
//     * @param ipAddr
//     * @throws SocketException
//     */
//    public CommunicateWordsWithUDP(String ipAddr) throws SocketException {
//        this.mIpAddr = ipAddr;
//    }
//
//    /**
//     * 使用udp发送消息
//     *
//     * @param str
//     */
//    public void sendDataWithUDPSocket(String str) {
//        try {
//            InetAddress serverAddress = InetAddress.getByName(mIpAddr);  // 初始化传入server ip
//            //byte data[] = str.getBytes(); // 数据传输是byte数组形式，需要先定义
//            String encrypt = AESUtils3.encrypt(str, "123456");
//            Log.v("TAG", "加密前: " + str);
//            // 加密字节数组
//            //byte[] encrypt = AESUtils3.encrypt(data, "123456");
//            Log.v("TAG", "加密后: " + encrypt);
//            DatagramPacket packet = new DatagramPacket(encrypt.getBytes(), encrypt.length(), serverAddress, 10025);
//            mSocket.send(packet);
//        } catch (SocketException e) {
//            e.printStackTrace();
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 客户端接收服务端返回的数据(保留方法，方便后期扩展)
//     */
//    public void ReceiveServerSocketData() {
//        DatagramSocket socket;
//        try {
//            socket = new DatagramSocket(1985);
//            byte data[] = new byte[4 * 1024];
//            DatagramPacket packet = new DatagramPacket(data, data.length);
//            socket.receive(packet);
//            String result = new String(packet.getData(), packet.getOffset(), packet.getLength());
//            socket.close();
//        } catch (SocketException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 接收消息的方法
//     */
//    public void ServerReceviedByUdp() {
//        DatagramSocket socket;
//        try {
//            socket = new DatagramSocket(10025);
//            while (true) {
//                byte data[] = new byte[4 * 1024];
//                DatagramPacket packet = new DatagramPacket(data, data.length);
//                socket.receive(packet);
//                String result = new String(data, 0, packet.getLength());
//                Log.v("TAG", "解密前: " + result);
//                // 解密
//                // byte[] decrypr = AESUtils3.decrypt(data, "123456");
//                String decrypr = AESUtils3.decrypt(result, "123456");
//                Log.v("TAG", "解密后: " + decrypr);
//                // String result = new String(decrypr, packet.getOffset(), packet.getLength());
//                if (!TextUtils.isEmpty(decrypr)) {
//                    WordsEvent wordsEvent = new WordsEvent(decrypr);
//                    EventBus.getDefault().post(wordsEvent);
//                }
//                System.out.println("收到信息为：" + decrypr);
//            }
//        } catch (SocketException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 关闭socket
//     */
//    public void disconnect() {
//        mSocket.close();
//        mSocket.disconnect();
//    }
//}








